package com.shh.aiojbackendserver.manager;

import com.shh.aiojbackendserver.constant.UserConstant;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.concurrent.TimeUnit;

/**
 * 限制不同用户生成ai题目次数
 * 非vip用户每日生成一条
 * vip用户每日生成五条
 * 管理员无限生成
 */
@Component
public class GenerationLimitManager {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    public boolean canGenerate(Long userId, String userRole) {
        String key = "gen:limit:" + userId + ":" + LocalDate.now().toString();
        int limit = userRole.equals(UserConstant.VIP_ROLE) ? 5 : 1;
        if(userRole.equals(UserConstant.ADMIN_ROLE)){
            limit=99999;
        }
        Long count = redisTemplate.opsForValue().increment(key);
        if (count == 1) {
            // 设置24小时过期
            redisTemplate.expire(key, 24, TimeUnit.HOURS);
        }
        return count <= limit;
    }
}
